import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Tag,
  Popconfirm,
  Typography,
  Row,
  Col,
  Modal,
  Tree,
  Tooltip,
  Badge,
  Spin,
  Drawer,
  Descriptions,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ApartmentOutlined,
  UserOutlined,
  EyeOutlined,
  TeamOutlined,
  ExpandOutlined,
  CompressOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { DataNode } from 'antd/es/tree';
import { Department, DepartmentForm as DepartmentFormType } from '@/types/rbac.ts';
import { useDepartmentTree, useDepartments } from '@/hooks/business/useDepartments';
import DepartmentForm from '../../components/DepartmentForm';

const { Title, Text } = Typography;
const { Search } = Input;

const Departments: React.FC = () => {
  // UI状态管理
  const [isFormModalVisible, setIsFormModalVisible] = useState(false);
  const [isViewDrawerVisible, setIsViewDrawerVisible] = useState(false);
  const [editingDepartment, setEditingDepartment] = useState<Department | null>(null);
  const [viewingDepartment, setViewingDepartment] = useState<Department | null>(null);
  const [expandedTreeKeys, setExpandedTreeKeys] = useState<string[]>([]);
  const [selectedTreeKeys, setSelectedTreeKeys] = useState<string[]>([]);
  const [isTreeExpanded, setIsTreeExpanded] = useState(true);

  // 使用增强后的hooks
  const { departmentTree, loading: treeLoading, refresh: refreshTree } = useDepartmentTree();
  const {
    departments,
    departmentManagers,
    loading,
    actionLoading,
    searchKeyword,
    createDepartment,
    updateDepartment,
    deleteDepartment,
    handleSearch,
    refresh,
  } = useDepartments({ autoLoad: true });

  // 工具函数
  const findDepartment = (depts: Department[], id: string): Department | null => {
    for (const dept of depts) {
      if (dept.id === id) return dept;
      if (dept.children) {
        const found = findDepartment(dept.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  const getParentDepartmentName = (parentId: string | number | null | undefined): string => {
    if (!parentId || parentId === '0' || parentId === 0) {
      return '无';
    }
    const parentDept = findDepartment(departmentTree, String(parentId));
    return parentDept ? parentDept.name : `未知部门(${parentId})`;
  };

  const getDepartmentIcon = (level: number) => {
    const icons = [
      <ApartmentOutlined style={{ color: '#1890ff' }} />,
      <TeamOutlined style={{ color: '#52c41a' }} />,
      <UserOutlined style={{ color: '#faad14' }} />,
    ];
    return icons[Math.min(level, icons.length - 1)] || <UserOutlined />;
  };

  // UI事件处理
  const handleAdd = () => {
    setEditingDepartment(null);
    setIsFormModalVisible(true);
  };

  const handleEdit = (department: Department) => {
    setEditingDepartment(department);
    setIsFormModalVisible(true);
  };

  const handleView = (department: Department) => {
    setViewingDepartment(department);
    setIsViewDrawerVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteDepartment(id);
      refreshTree();
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const handleFormSubmit = async (values: DepartmentFormType) => {
    try {
      if (editingDepartment) {
        await updateDepartment(editingDepartment.id, values);
      } else {
        await createDepartment(values);
      }
      setIsFormModalVisible(false);
      refreshTree();
    } catch (error) {
      console.error('提交失败:', error);
    }
  };

  const handleFormCancel = () => {
    setIsFormModalVisible(false);
    setEditingDepartment(null);
  };

  const handleTreeExpand = () => {
    if (isTreeExpanded) {
      setExpandedTreeKeys([]);
    } else {
      const getAllIds = (depts: Department[]): string[] => {
        let ids: string[] = [];
        depts.forEach(dept => {
          ids.push(dept.id);
          if (dept.children && dept.children.length > 0) {
            ids = ids.concat(getAllIds(dept.children));
          }
        });
        return ids;
      };
      setExpandedTreeKeys(getAllIds(departmentTree));
    }
    setIsTreeExpanded(!isTreeExpanded);
  };

  // 生命周期管理
  useEffect(() => {
    // 默认展开所有节点
    if (departmentTree.length > 0) {
      const getAllIds = (depts: Department[]): string[] => {
        let ids: string[] = [];
        depts.forEach(dept => {
          ids.push(dept.id);
          if (dept.children && dept.children.length > 0) {
            ids = ids.concat(getAllIds(dept.children));
          }
        });
        return ids;
      };
      setExpandedTreeKeys(getAllIds(departmentTree));
    }
  }, [departmentTree]);

  // 数据转换
  const convertToTreeData = (depts: Department[]): DataNode[] => {
    return depts.map(dept => ({
      key: dept.id,
      title: (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {getDepartmentIcon(dept.level || 0)}
          <span>{dept.name}</span>
          <Badge count={dept.memberCount || 0} size="small" />
          {dept.status === 0 && <Tag color="red">禁用</Tag>}
        </div>
      ),
      children: dept.children ? convertToTreeData(dept.children) : undefined,
    }));
  };

  // 获取选中部门及其所有子部门的ID
  const getSelectedDepartmentIds = (selectedId: string, depts: Department[]): string[] => {
    const ids: string[] = [];
    
    const findDepartmentAndChildren = (targetId: string, deptList: Department[]): void => {
      for (const dept of deptList) {
        if (dept.id === targetId) {
          ids.push(dept.id);
          if (dept.children) {
            const getAllChildIds = (children: Department[]): void => {
              children.forEach(child => {
                ids.push(child.id);
                if (child.children) {
                  getAllChildIds(child.children);
                }
              });
            };
            getAllChildIds(dept.children);
          }
          return;
        }
        if (dept.children) {
          findDepartmentAndChildren(targetId, dept.children);
        }
      }
    };
    
    findDepartmentAndChildren(selectedId, depts);
    return ids;
  };

  // 过滤部门数据
  const filteredDepartments = departments.filter(dept => {
    // 搜索关键词过滤
    const matchesSearch = !searchKeyword || dept.name.toLowerCase().includes(searchKeyword.toLowerCase());
    
    // 选中部门过滤
    if (selectedTreeKeys.length === 0) {
      // 没有选中任何部门时，显示所有符合搜索条件的部门
      return matchesSearch;
    } else {
      // 选中部门时，显示选中部门及其子部门中符合搜索条件的部门
      const selectedId = selectedTreeKeys[0]; // 取第一个选中的部门
      const selectedDepartmentIds = getSelectedDepartmentIds(selectedId, departmentTree);
      return matchesSearch && selectedDepartmentIds.includes(dept.id);
    }
  });

  // 表格列定义
  const columns: ColumnsType<Department> = [
    {
      title: '部门信息',
      key: 'info',
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {getDepartmentIcon(record.level || 0)}
          <div>
            <div style={{ fontWeight: 500 }}>{record.name}</div>
            <div style={{ fontSize: 12, color: '#666' }}>编码: {record.code}</div>
          </div>
        </div>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true,
      render: (text) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个部门吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 页面标题 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <ApartmentOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            部门管理
          </Title>
          <Text type="secondary">管理组织架构和部门信息</Text>
        </div>
        <Space>
          <Search
            placeholder="搜索部门名称或代码"
            allowClear
            style={{ width: 300 }}
            onSearch={handleSearch}
            value={searchKeyword}
          />
          <Button 
            icon={<ReloadOutlined />} 
            onClick={() => {
              refresh();
              refreshTree();
            }}
            loading={loading}
            style={{
              borderColor: '#d9d9d9',
              color: '#666'
            }}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={handleAdd}
            style={{ borderRadius: 6 }}
          >
            新建部门
          </Button>
        </Space>
      </div>

      <Card bodyStyle={{ padding: 0 }}>

        {/* 主内容区域 */}
        <div style={{ padding: '0 24px 24px 24px' }}>
          <Row gutter={16}>
            {/* 左侧部门树 */}
            <Col span={6}>
              <Card 
                title={
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <ApartmentOutlined />
                    <span>组织架构</span>
                    <Badge count={departmentTree.length} style={{ backgroundColor: '#64748b' }} />
                  </div>
                }
                extra={
                  <Space>
                    <Button 
                      size="small" 
                      onClick={handleTreeExpand}
                    >
                      {isTreeExpanded ? '全部收起' : '全部展开'}
                    </Button>
                  </Space>
                }
                style={{ height: '600px', overflow: 'auto' }}
                bodyStyle={{ height: 'calc(100% - 57px)', overflow: 'auto', padding: '16px' }}
              >
                {treeLoading ? (
                  <div style={{ textAlign: 'center', padding: 50 }}>
                    <Spin size="large" />
                    <div style={{ marginTop: 16, color: '#666' }}>加载中...</div>
                  </div>
                ) : (
                  <Tree
                    showLine
                    showIcon
                    expandedKeys={expandedTreeKeys}
                    selectedKeys={selectedTreeKeys}
                    onSelect={(keys) => setSelectedTreeKeys(keys as string[])}
                    onExpand={(keys) => setExpandedTreeKeys(keys as string[])}
                    treeData={convertToTreeData(departmentTree)}
                  />
                )}
              </Card>
            </Col>

            {/* 右侧部门表格 */}
            <Col span={18}>
              <Table
                columns={columns}
                dataSource={filteredDepartments}
                loading={loading}
                rowKey="id"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total, range) =>
                    `第 ${range?.[0]}-${range?.[1]} 条，共 ${total} 条记录`,
                }}
                scroll={{ x: 1200 }}
              />
            </Col>
          </Row>
        </div>
      </Card>

      {/* 部门表单Modal */}
      <DepartmentForm
         visible={isFormModalVisible}
         department={editingDepartment || undefined}
         departmentTree={departmentTree}
         treeLoading={treeLoading}
         loading={actionLoading}
         onSubmit={handleFormSubmit}
         onCancel={handleFormCancel}
       />

      {/* 部门详情Drawer */}
      <Drawer
        title={
          <Space>
            <EyeOutlined style={{ color: '#1890ff' }} />
            <span style={{ color: '#1890ff' }}>部门详情</span>
          </Space>
        }
        open={isViewDrawerVisible}
        onClose={() => setIsViewDrawerVisible(false)}
        width={600}
        extra={
          <Button 
            type="primary" 
            icon={<EditOutlined />}
            onClick={() => {
              setIsViewDrawerVisible(false);
              if (viewingDepartment) {
                handleEdit(viewingDepartment);
              }
            }}
          >
            编辑
          </Button>
        }
      >
        {viewingDepartment && (
          <Descriptions
            title="基本信息"
            bordered
            column={1}
            size="middle"
            style={{ marginBottom: 24 }}
          >
            <Descriptions.Item label="部门名称">
              <Space>
                {getDepartmentIcon(viewingDepartment.level || 0)}
                <span style={{ fontWeight: 500 }}>{viewingDepartment.name}</span>
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="部门代码">
              <Text style={{ fontFamily: 'monospace', backgroundColor: '#f5f5f5', padding: '2px 6px', borderRadius: 4 }}>
                {viewingDepartment.code}
              </Text>
            </Descriptions.Item>
            <Descriptions.Item label="上级部门">
              {getParentDepartmentName(viewingDepartment.parentId)}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={viewingDepartment.status === 1 ? 'green' : 'red'}>
                {viewingDepartment.status === 1 ? '启用' : '禁用'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="部门负责人">
              {viewingDepartment.managerId ? 
                (() => {
                  const manager = departmentManagers.find(m => m.id === viewingDepartment.managerId);
                  return manager ? (
                    <Space>
                      <UserOutlined style={{ color: '#1890ff' }} />
                      <span>{manager.realName || manager.username}</span>
                      {manager.email && (
                        <span style={{ color: '#999', fontSize: '12px' }}>({manager.email})</span>
                      )}
                    </Space>
                  ) : (
                    <span style={{ color: '#ff4d4f' }}>
                      <UserOutlined /> 用户不存在(ID: {viewingDepartment.managerId})
                    </span>
                  );
                })() : 
                <span style={{ color: '#999' }}>暂无</span>
              }
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {viewingDepartment.createTime ? new Date(viewingDepartment.createTime).toLocaleString() : '-'}
            </Descriptions.Item>
            {viewingDepartment.description && (
              <Descriptions.Item label="部门描述">
                {viewingDepartment.description}
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Drawer>
    </div>
  );
};

export default Departments;